/*
 ***************************************************************************
 *           Copyright © 2009 by konglinglong                              *
 *           konglinglong@gmail.com                                        *
 *           我的主页:https://sites.google.com/site/konglinglong/           *
 ***************************************************************************
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************
 */

#ifndef PACKETSTORAGE_H_
#define PACKETSTORAGE_H_

#include <QtCore>
#include "Longdefines.h"

class InPacket;
class OutPacket;
class PacketStorage : public QThread
{
	Q_OBJECT
public:
	PacketStorage(QObject *parent = 0);

	~PacketStorage();

	void run();

private slots:
	//收到timeout信号后检查needAckPacketList，重发要重发的包
	void checkNeedAckList();
	//发送心跳包(保持在线)
	void doKeepAlive();

public:
	//把包添加到队列中
	void appendInPacket(InPacket *inPacket);

	void appendInPacket(char *inStr, int32 len);
	//把包添加到队列中
	void appendOutPacket(OutPacket *outPacket);
	//通过顺序号从队列中删除包
	void removeOutPacketBySeq(unsigned short seq);
	//通过命令字从队列中删除包
	void removeOutPacketByCom(unsigned short com);
	//通过顺序号从队列中删除包
	void removeNeedAckPacketBySeq(unsigned short seq);
	//通过命令字从队列中删除包
	void removeNeedAckPacketByCom(unsigned short com);
	//
	void startKeepAliveTimer();
	//
	void stopKeepAliveTimer();

	//
	void deleteAllInPacket();
	//
	void deleteAllOutPacket();
	//
	void deleteAllNeedAckPacket();
	//
	void deleteAllPacket();
	//
	void doConnect();

private:
	//用于定时检查needAckPacketList中包的情况
	QTimer *checker;
	//定时器，每隔60秒种发送一个保持在线包
	QTimer *keepAliveTimer;
	//用于保护各个包队列
	QMutex mutex;
	//线程同步
	QWaitCondition packetListEmpty;
	//收到的包队列
	QHash<short, InPacket *> inPacketList;
	//发送的包队列
	QHash<short, OutPacket *> outPacketList;
	//需应答的包队列
	QHash<short, OutPacket *> needAckPacketList;
	//结束线程标志，当endThread==true时线程跳出无限循环
	bool endThreadFlag;

};

#endif /* PACKETSTORAGE_H_ */
